package com.wanghlme.day27.web;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.wanghlme.day27.filter.EncodingFilter;
import com.wanghlme.day27.pojo.Dept;
import com.wanghlme.day27.pojo.Emp;
import com.wanghlme.day27.service.ICompanyService;
import com.wanghlme.day27.service.impl.CompanyServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/toAddEmp")
public class InsertEmpAction extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(EncodingFilter.class.getName());
    private ICompanyService companyService;

    public InsertEmpAction() {
        companyService = new CompanyServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(), StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        String tmpStr = null;
        while ((tmpStr = reader.readLine()) != null) {
            sb.append(tmpStr);
        }
        String originStr = sb.toString();
        String[] handlerStr = originStr.split("&");
        int i = 0;
        Map<String, String> map = new HashMap<>();
        for (String str : handlerStr) {
            map.put(str.split("=")[0], str.split("=")[1]);
        }
        String empName = map.get("empName");
        String empHiredate = map.get("empHiredate");
        String deptId = map.get("dept");
        System.out.println(map.toString());
        Emp emp = new Emp();
        Dept dept = companyService.queryDeptById(Integer.parseInt(deptId));
        emp.setEmpName(empName);
        try {
            emp.setEmpHiredate(new SimpleDateFormat("yyyy-MM-dd").parse(empHiredate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        emp.setEmpStatus(1);
        emp.setDept(dept);
        System.out.println("====" + emp);
        Emp tmp = companyService.addEmp(emp);
        System.out.println("====" + tmp);
        System.out.println(emp);
        PrintWriter out = resp.getWriter();
        if (tmp != null) {
            out.print("1");
        } else {
            out.print("0");
        }
        out.flush();
        out.close();
    }
}
